<template>
  <div class="register-container">
    <div class="register-wrapper">
      <!-- 头部logo区域 -->
      <div class="register-header">
        <div class="logo-section">
          <div class="logo-placeholder">
            <el-icon size="60" color="#409EFF">
              <School />
            </el-icon>
          </div>
          <h1 class="system-title">毕业论文智能查重系统</h1>
          <p class="system-subtitle">用户注册</p>
        </div>
      </div>

      <!-- 注册表单区域 -->
      <div class="register-form-container">
        <el-card class="register-card" shadow="hover">
          <div class="form-header">
            <h2>创建新账号</h2>
            <p>请填写以下信息完成注册</p>
          </div>

          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            label-width="0"
            @submit.prevent="handleRegister"
          >
            <!-- 用户类型选择 -->
            <el-form-item prop="userType">
              <el-radio-group v-model="registerForm.userType" class="user-type-group">
                <el-radio label="student" size="large">学生</el-radio>
                <el-radio label="teacher" size="large">教师</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 基本信息 -->
            <el-form-item prop="name">
              <el-input
                v-model="registerForm.name"
                placeholder="请输入真实姓名"
                size="large"
                clearable
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="account">
              <el-input
                v-model="registerForm.account"
                :placeholder="registerForm.userType === 'student' ? '请输入学号' : '请输入工号'"
                size="large"
                clearable
                :prefix-icon="Postcard"
              />
            </el-form-item>

            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱地址"
                size="large"
                clearable
                :prefix-icon="Message"
              />
            </el-form-item>

            <!-- 学生特有字段 -->
            <template v-if="registerForm.userType === 'student'">
              <el-form-item prop="major">
                <el-select
                  v-model="registerForm.major"
                  placeholder="请选择专业"
                  size="large"
                  clearable
                  filterable
                  class="full-width"
                >
                  <el-option
                    v-for="major in majorOptions"
                    :key="major"
                    :label="major"
                    :value="major"
                  />
                </el-select>
              </el-form-item>

              <el-form-item prop="className">
                <el-input
                  v-model="registerForm.className"
                  placeholder="请输入班级（如：计科2021-1班）"
                  size="large"
                  clearable
                  :prefix-icon="School"
                />
              </el-form-item>
            </template>

            <!-- 教师特有字段 -->
            <template v-if="registerForm.userType === 'teacher'">
              <el-form-item prop="department">
                <el-select
                  v-model="registerForm.department"
                  placeholder="请选择部门"
                  size="large"
                  clearable
                  filterable
                  class="full-width"
                >
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept"
                    :label="dept"
                    :value="dept"
                  />
                </el-select>
              </el-form-item>
            </template>

            <!-- 密码设置 -->
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码（6-20位）"
                size="large"
                show-password
                clearable
                :prefix-icon="Lock"
              />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                show-password
                clearable
                :prefix-icon="Lock"
                @keyup.enter="handleRegister"
              />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                class="register-btn"
                @click="handleRegister"
              >
                {{ loading ? '注册中...' : '立即注册' }}
              </el-button>
            </el-form-item>

            <!-- 返回登录 -->
            <el-form-item>
              <div class="form-footer">
                <span>已有账号？</span>
                <el-link type="primary" @click="$router.push('/login')">
                  立即登录
                </el-link>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="register-background">
      <div class="bg-shape shape-1"></div>
      <div class="bg-shape shape-2"></div>
      <div class="bg-shape shape-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock, School, Message, Postcard } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { register } from '@/api/auth'

const router = useRouter()

// 表单引用
const registerFormRef = ref()

// 加载状态
const loading = ref(false)

// 注册表单数据
const registerForm = ref({
  userType: 'student',
  name: '',
  account: '',
  email: '',
  major: '',
  className: '',
  department: '',
  password: '',
  confirmPassword: ''
})

// 专业选项
const majorOptions = [
  '计算机科学与技术',
  '软件工程',
  '网络工程',
  '数据科学与大数据技术',
  '人工智能',
  '信息安全',
  '物联网工程',
  '数字媒体技术'
]

// 部门选项
const departmentOptions = [
  '计算机学院',
  '软件学院',
  '信息学院',
  '数据科学学院',
  '人工智能学院'
]

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules = {
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
    { pattern: /^\d{9}$/, message: '学号/工号格式不正确（应为9位数字）', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  major: [
    { 
      required: true, 
      message: '请选择专业', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (registerForm.value.userType === 'student' && !value) {
          callback(new Error('请选择专业'))
        } else {
          callback()
        }
      }
    }
  ],
  className: [
    { 
      required: true, 
      message: '请输入班级', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (registerForm.value.userType === 'student' && !value) {
          callback(new Error('请输入班级'))
        } else {
          callback()
        }
      }
    }
  ],
  department: [
    { 
      required: true, 
      message: '请选择部门', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (registerForm.value.userType === 'teacher' && !value) {
          callback(new Error('请选择部门'))
        } else {
          callback()
        }
      }
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    // 表单验证
    await registerFormRef.value.validate()
    
    loading.value = true
    
    // 构造注册数据
    const registerData = {
      account: registerForm.value.account,
      password: registerForm.value.password,
      email: registerForm.value.email,
      name: registerForm.value.name,
      userType: registerForm.value.userType,
      major: registerForm.value.major || null,
      className: registerForm.value.className || null,
      department: registerForm.value.department || null
    }
    
    console.log('注册请求数据:', JSON.stringify(registerData, null, 2))
    
    // 调用注册API
    const response = await register(registerData)
    
    // 修改响应处理逻辑
    if (response.code === 200) {
      ElMessage.success(response.message || '注册成功，请登录')
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      ElMessage.error(response.message || '注册失败')
    }
    
  } catch (error) {
    console.error('注册失败详情:', error)
    // 处理不同类型的错误
    if (error.response?.status === 403) {
      ElMessage.error('注册失败：访问被拒绝，请检查网络环境或联系管理员')
    } else if (error.response?.status === 400) {
      // 处理业务逻辑错误
      const errorMsg = error.response?.data?.message || '注册信息有误，请检查填写内容'
      ElMessage.error(errorMsg)
    } else if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络连接失败，请检查服务器状态')
    } else {
      ElMessage.error(error.message || '注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  padding: 2rem 0;
}

.register-wrapper {
  width: 100%;
  max-width: 450px;
  z-index: 10;
}

/* 头部logo区域 */
.register-header {
  text-align: center;
  margin-bottom: 2rem;
}

.logo-section {
  color: white;
}

.logo-placeholder {
  margin-bottom: 1rem;
}

.system-title {
  font-size: 1.8rem;
  font-weight: 600;
  margin: 0 0 0.5rem 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.system-subtitle {
  font-size: 1rem;
  opacity: 0.9;
  margin: 0;
}

/* 注册表单区域 */
.register-form-container {
  padding: 0 1rem;
}

.register-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 1.5rem;
}

.form-header h2 {
  color: #303133;
  margin: 0 0 0.5rem 0;
  font-weight: 600;
}

.form-header p {
  color: #909399;
  margin: 0;
  font-size: 0.9rem;
}

.register-form {
  padding: 0 1rem;
}

.user-type-group {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 2rem;
  padding: 1rem 0;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.full-width {
  width: 100%;
}

.register-btn {
  width: 100%;
  height: 48px;
  font-size: 1rem;
  font-weight: 500;
  border-radius: 8px;
}

.form-footer {
  text-align: center;
  font-size: 0.9rem;
  color: #909399;
}

/* 背景装饰 */
.register-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 15%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 80px;
  height: 80px;
  top: 75%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 160px;
  height: 160px;
  bottom: 10%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-wrapper {
    max-width: 90%;
  }
  
  .system-title {
    font-size: 1.5rem;
  }
  
  .register-form {
    padding: 0;
  }
  
  .user-type-group {
    gap: 1rem;
  }
}
</style>